

package com.aglhz.nature.presenter;

import java.net.URLDecoder;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

import com.aglhz.nature.constants.ServerAPI;
import com.aglhz.nature.events.MainViewEvent;
import com.aglhz.nature.events.MyselfViewEvent;
import com.aglhz.nature.modle.AddressBean;
import com.aglhz.nature.modle.CheckAccessToken;
import com.aglhz.nature.modle.CodeBean;
import com.aglhz.nature.modle.UserInfo;
import com.aglhz.nature.modle.WXAccessToken;
import com.aglhz.nature.modle.WXUserInfo;
import com.aglhz.nature.modle.item.UserInfoData;
import com.aglhz.nature.presenter.base.BasePresenter;
import com.aglhz.nature.utils.AsyncHttpCilentUtil;
import com.aglhz.nature.view.iv.MyselfView;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import cz.msebera.android.httpclient.cookie.Cookie;
import cz.msebera.android.httpclient.entity.StringEntity;
import cz.msebera.android.httpclient.util.TextUtils;

public class MyselfPresenter extends BasePresenter {
	private String openid;
	private String access_token;
	private String unionid;
	private String nickname;
	private String headimgurl;
	
	private int code;

	private static String TAG = MyselfPresenter.class.getName();

	// view
	private MyselfView myselfView;
	
	// data
	private CheckAccessToken checkAccessToken;
	private CodeBean codeBean;
	private WXUserInfo wxUserInfo;
	private WXAccessToken wxAccessToken;
	private UserInfo userInfo;
	private UserInfoData data;
	private AddressBean addressBean;
	

	public MyselfPresenter(MyselfView  view, Context context) {
		super();
		myselfView = view;
		super.setContext(context);
	}






	 //检测登录接口
	 public void loginCheck(String token) {
	 Log.e("-------to this--------loginCheck_________________","----------------loginCheck---------logincheck----------");
	 String url =
	 ServerAPI.APIHEARD+ServerAPI.LOGINCHECK+"?token="+token;
	 Log.e("loginCheck","--------"+url);
	 AsyncHttpClient client =  AsyncHttpCilentUtil.getInstance(super.getContext());
	 client.post(url, new TextHttpResponseHandler() {	
	 @Override
	 public void onSuccess(int statusCode,
	 cz.msebera.android.httpclient.Header[] headers,
	 String responseString) {
	 try {
	 Log.e(TAG, "response LogChecked" + responseString);
	
	 Gson gson = new Gson();
	
	 UserInfo uInfo = gson.fromJson(responseString,
			 UserInfo.class);
	 userInfo = (UserInfo) uInfo.clone();
	 code = Integer.parseInt(userInfo.getOther().getCode());
	 if (code == 200) {
		 getUserInfotwo();
	 } else {
		 myselfView.ClearInfo();
		
	 }
	
	 Log.e(TAG, "success" + "ddddddddddddddddddsuccess");
	 } catch (Exception e) {
	 e.printStackTrace();
	 }
	
	 }
	
	 @Override
	 public void onFailure(int statusCode,
	 cz.msebera.android.httpclient.Header[] headers,
	 String responseString, Throwable throwable) {
	
	 Log.e(TAG, "failure");
	 }
	
	 });
	
	 }

	// /*********************view operation*******************///
	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onEventMyselfThread(MyselfViewEvent event) {

		String msg = event.getMessage();
		Log.i(TAG, "MyselfViewEvent:" + msg);
		// update UI By event
		if (MyselfViewEvent.EVENT_UPDATE_LOGIN_VIEW == msg) {
		
			myselfView.ClearInfo();
			//新保存了token
			myselfView.SaveInfo();
			this.loginCheck(getToken());
//			this.getUserInfotwo();
		}else if (MyselfViewEvent.EVENT_UPDATE_LOGIN2_VIEW == msg) {
			this.getUerNickName();
			this.getUserName();
			this.getUserIcon();
			myselfView.saveAllInfo();
			this.showUserView();
		}else if (MyselfViewEvent.EVENT_UPDATE_ADDRESS_VIEW == msg) {
			myselfView.setAddressSize(addressBean.getData().size());
		}
	}
//展示数据
	public void showUserView() {

			myselfView.setHeadimage(userInfo.getData().getIcon());
			myselfView.setBgImage(userInfo.getData().getBgImage());
			myselfView.setUserName(userInfo.getData().getName());
			myselfView.setMembersInfo(0,0,0,0,0,userInfo.getData().getPoint(),userInfo.getData().getCardNumber(), userInfo.getData().getMoney());		
			


	}


	public String getToken() {
		return wxUserInfo.getData().getMemberInfo().getToken();
	}
	public String getNmae(){
		return wxUserInfo.getData().getMemberInfo().getName();
	}
	public String getNickName(){
		if(wxUserInfo.getData().getMemberInfo().getName()==""){
			return null;
		}
		return wxUserInfo.getData().getMemberInfo().getName();
	}
//userinfo
	public String getUerNickName(){
		return userInfo.getData().getNickName();
	}
	public String getUserName(){
		return userInfo.getData().getName();
	}
	public String getUserIcon(){
		return userInfo.getData().getIcon();
	}

	 /** 
     * 获取标准 Cookie   
     */  
    private String getCookieText() {  
        PersistentCookieStore myCookieStore = new PersistentCookieStore(super.getContext());  
        List<Cookie> cookies = myCookieStore.getCookies();  
        Log.d(TAG, "cookies.size() = " + cookies.size());  
       
        for (Cookie cookie : cookies) {  
            Log.d(TAG, cookie.getName() + " = " + cookie.getValue());  
        }  
         StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < cookies.size(); i++) {  
             Cookie cookie = cookies.get(i);  
             String cookieName = cookie.getName();  
             String cookieValue = cookie.getValue();  
            if (!TextUtils.isEmpty(cookieName)  
                    && !TextUtils.isEmpty(cookieValue)) {  
                sb.append(cookieName + "=");  
                sb.append(cookieValue + ";");  
            }  
        }  
        Log.e("cookie", sb.toString());  
        return sb.toString();  
    }  
  
//登陆后，获取信息
	public void  getUserInfotwo(){
		String url=ServerAPI.APIHEARD+ServerAPI.PRESONINFO;
		
		AsyncHttpClient client =  AsyncHttpCilentUtil.getInstance(super.getContext());
		client.post(url, new TextHttpResponseHandler() {
 
			@Override
			public void onSuccess(int statusCode,
					cz.msebera.android.httpclient.Header[] headers,
					String responseString) {
				try {
					Log.e(TAG, "responseAAA" + responseString);
					Gson gson = new Gson();

					UserInfo UInfo = gson.fromJson(responseString,
							UserInfo.class);
					userInfo = (UserInfo) UInfo.clone();
					Log.e("-------private void getUserInfo2() ",
							"--------url---------------" + userInfo);
					
					
						// send event
						MyselfViewEvent event = new MyselfViewEvent(
								MyselfViewEvent.EVENT_UPDATE_LOGIN2_VIEW);
						EventBus.getDefault().post(event);

					

					Log.e(TAG, "success" + "success");
				} catch (Exception e) {
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(int statusCode,
					cz.msebera.android.httpclient.Header[] headers,
					String responseString, Throwable throwable) {

				Log.e(TAG, "failure");
			}

		});

	}

	
	public void getAddressSize(String token){
String url=ServerAPI.APIHEARD+ServerAPI.ADDRESS+"?token="+token;
		
		AsyncHttpClient client =  AsyncHttpCilentUtil.getInstance(super.getContext());
		client.post(url, new TextHttpResponseHandler() {
 
			@Override
			public void onSuccess(int statusCode,
					cz.msebera.android.httpclient.Header[] headers,
					String responseString) {
				try {
					Log.e(TAG, "responseAAA" + responseString);
					Gson gson = new Gson();

					AddressBean addBean = gson.fromJson(responseString,
							AddressBean.class);
					addressBean = (AddressBean) addBean.clone();
					Log.e("-------private void getUserInfo2() ",
							"--------url---------------" + userInfo);
					
					
						// send event
						MyselfViewEvent event = new MyselfViewEvent(
								MyselfViewEvent.EVENT_UPDATE_ADDRESS_VIEW);
						EventBus.getDefault().post(event);

					

					Log.e(TAG, "success" + "success");
				} catch (Exception e) {
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(int statusCode,
					cz.msebera.android.httpclient.Header[] headers,
					String responseString, Throwable throwable) {

				Log.e(TAG, "failure");
			}

		});
	}
}

